package com.qianfeng.android.baoman;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.adapter.FindDownLoadBookAdapter;
import com.qianfeng.android.baoman.model.DownBooks;
import com.qianfeng.android.baoman.yxapi.DownLoadDetailActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DownLoadFindActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private int year;
    private int month;
    private LinearLayout load_layout;
    private List<DownBooks> downBookses;
    private FindDownLoadBookAdapter downLoadBookAdapter;
    private TextView dateTxt;
    private String url;
    private GridView cartoonGridView;
    private DatePickerDialog.OnDateSetListener listener;

    Calendar calendar = Calendar.getInstance();

    private void updateDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月");
        dateTxt.setText(dateFormat.format(calendar.getTime()));
        downLoadBookAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_down_load_find);

        initView();


        if (downBookses.size() == 0) {
            load_layout.setVisibility(View.VISIBLE);
        }


        url = "http://api.ibaozou.com/groups/19/outlineinfo/1/999/1.app" + "?year=" + calendar.get(Calendar.YEAR) + "&month=" + (calendar.get(Calendar.MONTH) + 1);
        getHttpData(url);


        //时间选择器
        listener = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {

                calendar.set(Calendar.YEAR, i);

                calendar.set(Calendar.MONTH, i2);

                year = i;
                month = i2 + 1;

                url = "http://api.ibaozou.com/groups/19/outlineinfo/1/999/1.app" + "?year=" + year + "&month=" + month;


//                if (cartoonGridView != null) {
//                    cartoonGridView.setAdapter(downLoadBookAdapter);
//
//                    if (url != null) {

                getHttpData(url);

                downBookses.clear();
//
//                    }
//                }

                updateDate();

            }
        };


    }

    private void initView() {
        ImageView backIcon = (ImageView) findViewById(R.id.find_download_top_back);
        backIcon.setOnClickListener(this);

        ImageView dateSelectBtn = (ImageView) findViewById(R.id.bookshop_date_select_btn);
        dateSelectBtn.setOnClickListener(this);

        load_layout = (LinearLayout) findViewById(R.id.load_layout);

        dateTxt = (TextView) findViewById(R.id.find_recourse_download_date_txt);

        //下载按钮
        ImageView downLoadBtn = (ImageView) findViewById(R.id.find_download_top_download_btn);
        downLoadBtn.setOnClickListener(this);

        downBookses = new LinkedList<DownBooks>();
        cartoonGridView = (GridView) findViewById(R.id.find_recourse_cartoon_download_grid_view);
        downLoadBookAdapter = new FindDownLoadBookAdapter(this, downBookses);
        cartoonGridView.setAdapter(downLoadBookAdapter);
        cartoonGridView.setOnItemClickListener(this);

    }


    private void getHttpData(String url) {

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(
                HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> jsonObjectResponseInfo) {


                        String result = jsonObjectResponseInfo.result;
                        List<DownBooks> downBook = new LinkedList<DownBooks>();
                        try {
                            JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                DownBooks book = new DownBooks();
                                book.parseJSON(jsonObject);
                                downBook.add(book);
                            }
                            load_layout.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        downBookses.addAll(downBook);
                        downLoadBookAdapter.notifyDataSetChanged();


                    }


                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(DownLoadFindActivity.this, "连接失败，网络问题", Toast.LENGTH_SHORT).show();
                        load_layout.setVisibility(View.GONE);
                    }
                }
        );
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.find_download_top_back:
                finish();
                break;

            case R.id.bookshop_date_select_btn:

                new DatePickerDialog(this,
                        listener,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH)
                ).show();

                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DownBooks downBooks = downBookses.get(position);
        String name = downBooks.getName();

        File sdCardPath = Environment.getExternalStorageDirectory();

        File cacheFile = new File(sdCardPath, "baozoumanhua");
        File targetFile = new File(cacheFile, name);
        File dirs = new File(cacheFile, "b" + name);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        if (targetFile.exists()) {
            String path = targetFile.getAbsolutePath();
            String path2 = dirs.getAbsolutePath();
            copyOfMyzipDecompressing(path, path2);
            Intent intent = new Intent(this, DownLoadDetailActivity.class);
            intent.putExtra("dirs", dirs);
            startActivity(intent);
        }
    }

    private void copyOfMyzipDecompressing(String path, String path2) {
        long startTime = System.currentTimeMillis();
        try {
            ZipInputStream Zin = new ZipInputStream(new FileInputStream(path));//输入源zip路径
            BufferedInputStream Bin = new BufferedInputStream(Zin);
            String Parent = path2; //输出路径（文件夹目录）
            File Fout = null;
            ZipEntry entry;
            try {
                while ((entry = Zin.getNextEntry()) != null && !entry.isDirectory()) {
                    Fout = new File(Parent, entry.getName());
                    if (!Fout.exists()) {
                        (new File(Fout.getParent())).mkdirs();
                    }
                    FileOutputStream out = new FileOutputStream(Fout);
                    BufferedOutputStream Bout = new BufferedOutputStream(out);
                    int b;
                    while ((b = Bin.read()) != -1) {
                        Bout.write(b);
                    }
                    Bout.close();
                    out.close();
                    System.out.println(Fout + "解压成功");
                }
                Bin.close();
                Zin.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗费时间： " + (endTime - startTime) + " ms");
    }

}
